"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : postgres_fdw
Case Name   : 分区表含4种NON-SPJ算子的强制下推
Create At   : 2023-01-06
Owner       : opentestcase004
Description :
    1.安装postgres_fdw扩展,创建外部服务器,用户映射,模式
    2.建基表
    3.创建外表
    4.向外表插入数据
    5.explain分析分区表含NON-SPJ算子进行强制下推是否成功
    6.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.下推成功,执行计划Remote SQL打印所有的agg,limit,LOCKROWS四种NON-SPJ算子均
      下推在远端执行
    6.成功
History     :
"""

import os
import unittest
from yat.test import Node
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class PostgresFdw(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info("-----------this is setup-----------")
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.pri_userdb = Node(node='PrimaryDbUser')
        self.commsh = CommonSH('PrimaryDbUser')
        self.tb_name1 = 't_postgres_fdw_foreign_0036_01'
        self.tb_name2 = 't_postgres_fdw_foreign_0036_02'
        self.server = 'se_postgres_fdw_foreign_0036'
        self.schema = 's_postgres_fdw_foreign_0036'
        self.port = self.pri_userdb.db_port
        self.database = self.pri_userdb.db_name

    def test_pub_sub(self):
        text = "--step1:安装postgres_fdw扩展,创建外部服务器,用户映射,模式" \
               "expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop extension if exists postgres_fdw cascade;" \
            f"create extension if not exists postgres_fdw;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_extension_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_extension_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop server if exists {self.server} cascade;" \
            f"create server {self.server} foreign data wrapper postgres_fdw " \
            f"options (dbname '{self.database}', port '{self.port}');"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_server_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_server_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop user mapping if exists for current_user server " \
            f"{self.server};create user mapping for current_user server " \
            f"{self.server};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_usermapping_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.create_usermapping_success, result,
                      '执行失败' + text)

        sql_cmd = f"drop schema if exists {self.schema} cascade;" \
            f"create schema {self.schema};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "--step2:建基表 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop table if exists {self.schema}.{self.tb_name1};" \
            f"create table {self.schema}.{self.tb_name1}(id int) " \
            f"partition by range(id)(" \
            f"  partition p1 values less than(120)," \
            f"  partition p2 values less than(250)," \
            f"  partition p3 values less than(600));"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, result, '执行失败' +
                      text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, result, '执行失败' +
                      text)

        text = "--step3:创建外表 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop foreign table if exists {self.tb_name2};" \
            f"create foreign table {self.tb_name2} (id int) server " \
            f"{self.server} options (schema_name '{self.schema}', table_name " \
            f"'{self.tb_name1}');"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.CREATE_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)

        text = "--step4:向外表插入数据 expect:成功--"
        self.log.info(text)
        sql_cmd = f"set sql_beta_feature TO 'partition_fdw_on';" \
            f"insert into {self.tb_name2} values(generate_series(1,500));" \
            f"analyse {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, result, '执行失败' +
                      text)
        self.assertIn(self.constant.ANALYZE_SUCCESS_MSG, result, '执行失败' +
                      text)

        text = "--step5:explain分析分区表含NON-SPJ算子进行强制下推是否成功 " \
               "expect:下推成功,执行计划Remote SQL打印所有的agg,limit," \
               "LOCKROWS四种NON-SPJ算子均下推在远端执行--"
        self.log.info(text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set enable_" \
            f"hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,costs off) select " \
            f"count(*) from {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-2]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT count(*) FROM '
                         f'{self.schema}.{self.tb_name1}', result_split1,
                         '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set enable_" \
            f"hashjoin=off;set enable_mergejoin=off;" \
            f"set enable_nestloop=off;explain (verbose,costs off) select " \
            f"sum(id) from {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-2]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT sum(id) FROM '
                         f'{self.schema}.{self.tb_name1}', result_split1,
                         '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,costs off) select " \
            f"max(id) from {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-2]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} WHERE ((id IS NOT '
                         f'NULL)) ORDER BY id DESC NULLS FIRST',
                         result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on'; set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,costs off) select " \
            f"min(id) from {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-2]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} WHERE ((id IS NOT '
                         f'NULL)) ORDER BY id ASC NULLS LAST',
                         result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,analyze) select * from " \
            f"{self.tb_name2} order by id;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-3]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} ORDER BY id ASC '
                         f'NULLS LAST', result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on'; set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,analyze) select * from " \
            f"{self.tb_name2} offset 5 limit 1;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-3]).strip()
        self.assertEqual(result.count('SET'), 5, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} LIMIT 1::bigint '
                         f'OFFSET 5::bigint', result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on'; set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,analyze) select * from " \
            f"{self.tb_name2} for update;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-3]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} FOR UPDATE',
                         result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,analyze) select * from " \
            f"{self.tb_name2} for share;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-3]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} FOR SHARE',
                         result_split1, '执行失败' + text)
        sql_cmd = f"set sql_beta_feature to 'partition_fdw_on';set " \
            f"enable_hashjoin=off;set enable_mergejoin=off;set " \
            f"enable_nestloop=off;explain (verbose,analyze) select * from " \
            f"{self.tb_name2} for key share;"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        result_split = result.splitlines()
        result_split1 = str(result_split[-3]).strip()
        self.assertEqual(result.count('SET'), 4, '执行失败' + text)
        self.assertEqual(f'Remote SQL: SELECT id FROM '
                         f'{self.schema}.{self.tb_name1} FOR SHARE',
                         result_split1, '执行失败' + text)

    def tearDown(self):
        text = "--step6:清理环境 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop extension if exists postgres_fdw cascade; " \
            f"drop server if exists {self.server} cascade;" \
            f"drop user mapping if exists for current_user server " \
            f"{self.server};drop schema if exists {self.schema} cascade;" \
            f"drop foreign table if exists {self.tb_name2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertIn(self.constant.drop_extension_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.drop_server_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.drop_usermapping_success, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.assertIn(self.constant.DROP_FOREIGN_SUCCESS_MSG, result,
                      '执行失败' + text)
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
